// 将时间戳处理为字符串
export function handleDateToString (time, showHMS) {
    if (!time) {
        return '--'
    } else {
        let date
        if (time instanceof Date) {
            date = time
        } else {
            date = new Date(time)
        }
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let minute = date.getMinutes()
        let second = date.getSeconds()
        month = month < 10 ? ('0' + month) : month
        day = day < 10 ? ('0' + day) : day
        hour = hour === 0 ? '00' : (hour < 10 ? '0' + hour : hour)
        minute = minute === 0 ? '00' : (minute < 10 ? '0' + minute : minute)
        second = second === 0 ? '00' : (second < 10 ? '0' + second : second)
        return year + '-' + month + '-' + day + (showHMS ? ' ' + hour + ':' + minute + ':' + second : '')
    }
}

/**
 * 最大余额法
 * 给定一个精度值，计算某一项在一串数据中占据的百分比，确保百分比总和是1（100%）
 * 使用最大余额法
 * Get a data of given precision, assuring the sum of percentages
 * in valueList is 1.
 * The largest remainer method is used.
 * https://en.wikipedia.org/wiki/Largest_remainder_method
 * https://qjzd.net/topic/59a3fee2b9fded0f2581c257
 * @param {Array.<number>} valueList a list of all data 一列数据
 * @param {number} idx index of the data to be processed in valueList 索引值（数组下标）
 * @param {number} precision integer number showing digits of precision 精度值
 * @return {number} percent ranging from 0 to 100 返回百分比从0到100
 */
export function getPercentWithPrecision(valueList, idx, precision) {
    if (!valueList[idx]) {
        return 0
    }

    let sum = valueList.reduce(function(acc, val) {
        return acc + (isNaN(val) ? 0 : val)
    }, 0)
    if (sum === 0) {
        return 0
    }
    // sum 9
    let digits = Math.pow(10, precision) // digits 100
    let votesPerQuota = valueList.map(function(val) {
        return ((isNaN(val) ? 0 : val) / sum) * digits * 100 // 扩大比例，这样可以确保整数部分是已经确定的议席配额，小数部分是余额
    })
    // votesPerQuota [ 2222.222222222222, 4444.444444444444, 3333.333333333333 ] 每一个项获得的议席配额，整数部分是已经确定的议席配额，小数部分是余额
    let targetSeats = digits * 100 // targetSeats 10000 全部的议席
    let seats = votesPerQuota.map(function(votes) {
        // Assign automatic seats.
        return Math.floor(votes)
    })
    // seats [ 2222, 4444, 3333 ] 获取配额的整数部分
    let currentSum = seats.reduce(function(acc, val) {
        return acc + val
    }, 0)
    // 9999 表示已经配额了9999个议席，还剩下一个议席
    let remainder = votesPerQuota.map(function(votes, idx) {
        return votes - seats[idx]
    })
    // [ 0.2222222222221717, 0.4444444444443434, 0.33333333333303017 ]得到每一项的余额
    // Has remainding votes. 如果还有剩余的坐席就继续分配
    while (currentSum < targetSeats) {
        // Find next largest remainder. 找到下一个最大的余额
        let max = Number.NEGATIVE_INFINITY
        let maxId = null
        for (let i = 0, len = remainder.length; i < len; ++i) {
            if (remainder[i] > max) {
                max = remainder[i]
                maxId = i
            }
        }
        // max: 0.4444444444443434, maxId 1
        // Add a vote to max remainder.
        ++seats[maxId] // 第二项，即4的占比的坐席增加1
        remainder[maxId] = 0
        ++currentSum // 总的已分配的坐席数也加1
    }

    return seats[idx] / digits
}

export function formatDate (date, format) {
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S': date.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (let k in o) {
        if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
        }
    }
    return format
}
